﻿using DAL.Repositories;
using ggHD.Domain.BizObj;
using ggHD.Domain.Repisitories;
using LinqToDB;
using LinqToDB.Data;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ggHD.DAL.Repositories
{
    internal class TicketRepository : ITicketRepository
    {
        private Repository<TicketHeader, int> _headerRepository;
        //private Repository<TicketC, int> _headerRepository;
        private IRawMailRepository _mailRep;
        private DataConnection _context;
        private IExternalInitiatorRepository _extInitRep;

        public TicketRepository(IDataContext context)
        {
            _headerRepository = new Repository<TicketHeader, int>(context);
            _context = (DataConnection)context;
            _mailRep = new RawMailRepository(context);
        }

        public int CreateFromRawMail(long mailId)
        {
            if (mailId < 1)
                return -1;

            var mail = _mailRep.Get(mailId);

            if (mail == null)
                throw new TicketRepositoryException(string.Format("Письмо с ID={0} не найдено", mailId));

            var initiatorId = _context.Execute<int?>("select id from ExternalInitiators where FromAddress = @addr"
                , new DataParameter("@addr", mail.FromAddress));

            var custId = _context.Execute<int>("select Id from Customers where email = @email", DataParameter.NVarChar("@email", mail.FromAddress));
            
            var header = new TicketHeader()
            {
                DateCreate = DateTime.Now,
                Header = mail.MsgSubject,
                RawMailId = mailId,
                InitiatorID = initiatorId,
                CustomerID = custId.ToString()
            };
            
            return _headerRepository.Insert(header);
        }

        public IEnumerable<TicketHeader> SelectHeaders(Func<TicketHeader, bool> pred)
        {
            return _headerRepository.Select(pred);
        }

        public IEnumerable<TicketHeader> AllHeaders()
        {
            return _headerRepository.All.ToArray();
        }
        
    }
}